<template>
	<div class="myMap" v-if="!item.common.isHidden" :style="commonStyle">
		<!-- #ifdef MP -->
		<map class="map" v-if="item.common.lat" @callouttap="markertap" @markertap="markertap"
			:latitude="item.common.lat*1" :longitude="item.common.lng*1" :scale="item.common.scale*1"
			:min-scale="item.common.minScale*1" :max-scale="item.common.maxScale*1" :markers="markers" :show-location="item.common.autoPosition">
			<!-- <cover-view slot="callout">
				<cover-view v-for="marker in markers" :key="marker.id" :marker-id="marker.id" :style="marker.style">
					{{marker.content}}
				</cover-view>
			</cover-view> -->
		</map>
		<!-- #endif -->
		<!-- #ifdef H5 -->
		<div class="map" :id="item.cid"></div>
		<!-- #endif -->
		<div class="tools">
			<div v-for="(widget,index) in widgetList" :key="widget.cid" @tap="ImgClick($event,index)">
				<myImg v-if="widget.type === 'pic'" :ref="widget.type+widget.cid" :pcid="widget.cid" :pageConfig="pageConfig"></myImg>
			</div>
		</div>
	</div>
</template>

<script>
	import calcBaseStyle from '../libs/calcBaseStyle'
	import { sendAjaxRequest, getKeyData } from '../libs/utils.js';
	import myImg from './myImg.vue';
	import coordtransform from '../libs/coordtransform';
	export default {
		name: 'myMap',
		components:{myImg},
		props:{
			pageConfig: {
				type: Object,
				default(){
					return {}
				}
			},
			pcid: null
		},
		inject: ['options'],
		data() {
			return {
				item: {
					common: {
						isHidden: false,
						markers: []
					},
					style: {},
					children: []
				},
				widgetList: [],
				// #ifdef H5
				mapInstance: null,
				aMarkers: [],
				ifCreated: false
				// #endif
			}
		},
		// #ifdef H5
		watch: {
			'item.common.isHidden'(newVal){
				if(!newVal && this.ifCreated){
					this.afterCreated()
				}else if(newVal){
					this.mapInstance = null
				}
			}
		},
		// #endif
		created() {
			this.$parent.widgetList.some(widget=>{
				if(widget.cid === this.pcid){
					this.item = widget
					this.afterCreated()
					// #ifdef H5
					setTimeout(()=>{
						this.ifCreated = true
					})
					// #endif
					return true
				}
			})
		},
		computed: {
			commonStyle(){
				return calcBaseStyle(this.item,this.pageConfig.contentH)
			},
			markers() {
				if (this.item.common.markers.length === 0) {
					return []
				}
				var markers = []
				this.item.common.markers.forEach((marker, index) => {
					if (!marker.lat || !marker.lng) {
						return
					}
					var newMarker = {
						id: index,
						latitude: marker.lat,
						longitude: marker.lng,
						iconPath: marker.iconPath,
						width: uni.upx2px(marker.width || 0),
						height: uni.upx2px(marker.height || 0),
						// #ifdef H5
						// 以下四个字段给H5端高德地图使用
						style: 'color:' + this.item.common.labelColor + ';font-size:' + uni.upx2px(this
								.item.common.fontSize) + 'px;text-align:center;border:solid ' + uni.upx2px(
								this.item.common.borderWidth) + 'px ' + this.item.common.borderColor +
							';border-radius:' + uni.upx2px(this.item.common.borderRadius) +
							'px;background-color:' + this.item.common.bgColor + ';padding:' + uni.upx2px(
								this.item.common.padding) + 'px;',
						content: marker.text,
						anchorX: uni.upx2px(marker.anchorX || 0),
						anchorY: uni.upx2px(marker.anchorY || 0),
						// 以上四个字段给H5端高德地图使用
						// #endif
						// #ifdef MP
						// 由于callout和customCallout的显示都有bug,所以最终小程序端选用title
						title: marker.text,
						// 以下两个字段给小程序端使用，由于callout和customCallout的显示都有bug，暂时不启用
						// callout: {
						// 	content: marker.text,
						// 	color: this.item.common.labelColor,
						// 	fontSize: uni.upx2px(this.item.common.fontSize),
						// 	borderRadius: uni.upx2px(this.item.common.borderRadius),
						// 	borderWidth: uni.upx2px(this.item.common.borderWidth),
						// 	borderColor: this.item.common.borderColor,
						// 	bgColor: this.item.common.bgColor,
						// 	padding: uni.upx2px(this.item.common.padding),
						// 	display: 'ALWAYS',
						// 	anchorX: uni.upx2px(marker.anchorX || 0),
						// 	anchorY: uni.upx2px(marker.anchorY || 0),
						// }
						// customCallout: {
						// 	display: 'ALWAYS',
						// 	anchorX: uni.upx2px(marker.anchorX || 0),
						// 	anchorY: uni.upx2px(marker.anchorY || 0),
						// }
						// 以上两个字段给小程序端使用
						// #endif
					}
					markers.push(newMarker)
				})
				return markers
			}
		},
		// #ifdef H5
		beforeDestroy() {
			this.mapInstance && this.mapInstance.destroy();
		},
		// #endif
		methods: {
			afterCreated(){
				this.widgetList = this.item.children
				this.renderContent()
				// #ifdef MP
				this.getAjaxSpots()
				this.getNowPosition()
				// #endif
				// #ifdef H5
				if(this.item.common.isHidden){
					return
				}
				this.initAmap()
				// #endif
				uni.$off('sendAjax-' + this.pageConfig.cid + '-' + this.item.cid)
				uni.$on('sendAjax-' + this.pageConfig.cid + '-' + this.item.cid, ()=>{
					this.getAjaxSpots()
					// #ifdef H5
					this.mapInstance.remove(this.aMarkers)
					// #endif
				})
			},
			renderContent(){
				this.widgetList.forEach(widget=>{
					var singleWidget = this.$refs[widget.type+widget.cid] || []
					singleWidget.forEach(item=>{
						item.item = widget
					})
				})
			},
			ImgClick(e,index){
				var dom = this.widgetList[index]
				if(dom.cid === this.item.common.locIcon){
					// #ifdef MP
					this.getNowPosition(true)
					// #endif
				}else if(dom.cid === this.item.common.bigIcon){
					this.item.common.scale = this.item.common.scale*1+1
					if(this.item.common.scale > this.item.common.maxScale*1){
						this.item.common.scale = this.item.common.maxScale*1
					}
					// #ifdef H5
					this.mapInstance.setZoom(this.item.common.scale)
					// #endif
				}else if(dom.cid === this.item.common.smaIcon){
					this.item.common.scale = this.item.common.scale*1-1
					if(this.item.common.scale < this.item.common.minScale*1){
						this.item.common.scale = this.item.common.minScale*1
					}
					// #ifdef H5
					this.mapInstance.setZoom(this.item.common.scale)
					// #endif
				}
			},
			// #ifdef H5
			initAmap() {
				if (!document.getElementById(this.item.cid)) {
					this.$nextTick(()=>{
						this.initAmap()
					})
					return
				}
				if (!this.mapInstance) {
					this.mapInstance = new AMap.Map(this.item.cid, {
						rotateEnable: false
					})
				}
				this.mapInstance.setCenter([this.item.common.lng || 116.397445, this.item.common.lat || 39.909138])
				this.mapInstance.setZoom(this.item.common.scale)
				this.mapInstance.setZooms([this.item.common.minScale, this.item.common.maxScale])
				this.mapInstance.remove(this.aMarkers)
				if(!this.item.ajax || this.item.ajax.length === 0){
					this.addMarkers()
				}else{
					this.getAjaxSpots()
				}
			},
			addMarkers(){
				this.aMarkers = []
				this.markers.forEach(marker => {
					var icon = new AMap.Icon({
						// 图标尺寸
						size: new AMap.Size(marker.width, marker.height),
						// 图标的取图地址
						image: marker.iconPath,
						// 图标所用图片大小
						imageSize: new AMap.Size(marker.width, marker.height),
						// 图标取图偏移量
						imageOffset: new AMap.Pixel(0, 0)
					});
					var newMarker = new AMap.Marker({
						position: [marker.longitude, marker.latitude],
						icon,
						anchor: 'bottom-center',
						label: {
							content: '<div style="' + marker.style + '">' + marker.content + '</div>',
							offset: new AMap.Pixel(marker.anchorX, marker.anchorY),
							direction: 'top'
						}
					});
					this.mapInstance.add(newMarker)
					this.aMarkers.push(newMarker)
					newMarker.on('click', () => {
						this.markertap({
							detail: {
								markerId: marker.id
							}
						})
					})
				})
			},
			// #endif
			// #ifdef MP
			getNowPosition(byClick){
				if(byClick){
					this.getNowLocation()
				}else if(this.item.common.autoPosition){
					this.getNowLocation()
				}
			},
			getNowLocation(){
				var modalParserLocTime = uni.getStorageSync('modalParserLocTime'),timeVal = new Date().getTime() - modalParserLocTime
				if(timeVal > 1000 * 60){
					uni.getLocation({
						type:'gcj02',
						success: res =>{
							console.log('定位成功',res);
							uni.setStorageSync('modalParserLng',res.longitude)
							uni.setStorageSync('modalParserLat',res.latitude)
							uni.setStorageSync('modalParserLocTime',new Date().getTime())
							this.item.common.lng = res.longitude
							this.item.common.lat = res.latitude
						},
						fail: res =>{
							console.log('定位失败',res);
						}
					})
				}else{
					var modalParserLng = uni.getStorageSync('modalParserLng'),modalParserLat = uni.getStorageSync('modalParserLat');
					uni.setStorageSync('modalParserLocTime',new Date().getTime())
					this.item.common.lng = modalParserLng
					this.item.common.lat = modalParserLat
					console.log('从缓存中获取定位',modalParserLng,modalParserLat);
				}
			},
			// #endif
			getAjaxSpots(){
				if(this.item.ajax && this.item.ajax.length > 0){
					this.item.common.markers = []
					sendAjaxRequest(this.item.ajax[0], this.options, '', this.pageConfig.variable, this.pageConfig.cid, this.pageConfig).then(res => {
						var markers = [];
						res.listData.forEach(spot=>{
							var obj = {}
							res.bindData.forEach(bind=>{
								var key = bind.originKey.split('%krt_').slice(-1)[0]
								var val = getKeyData(bind.bindKey, spot, 1)
								obj[key] = val
							})
							var cs = this.transformCs(this.item.common.csType,obj.lng,obj.lat)
							obj.lng = cs[0]
							obj.lat = cs[1]
							markers.push(obj)
						})
						this.item.common.markers = markers
						// #ifdef H5
						this.addMarkers()
						// #endif
					})
				}
			},
			transformCs(csType,lng,lat){
				if(!lng || !lat){
					return 0
				}
				var lngLat = [lng,lat]
				if(csType === 'BD09'){
					lngLat = coordtransform.bd09togcj02(lng,lat)
				}else if(csType === 'WGS84'){
					lngLat = coordtransform.wgs84togcj02(lng,lat)
				}
				return lngLat
			},
			markertap(e) {
				uni.navigateTo({
					url: this.item.common.url + this.item.common.markers[e.detail.markerId].id
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	.myMap {
		position: absolute;
		overflow: hidden;

		.map {
			width: 100%;
			height: 100%;
		}
	}
</style>
